<template>
	<div>
		<div class="box">
			<uni-forms
				ref="form"
				:model="plan"
				validate-trigger="bind"
				:label-position="state == 'write' ? 'top' : 'left'"
				label-width="auto">
				<FromItem
					label="支付频率"
					:required="true"
					:state="state"
					name="planPaymentFrequencyType">
					<ASelectUni
						:dict="{
							list: dict.type.quota_plan_payment_frequency_type,
						}"
						:state="state"
						v-model="plan.planPaymentFrequencyType"></ASelectUni>
				</FromItem>
				<FromItem
					label="租赁期限(月）"
					:required="true"
					:state="state"
					name="planTenancyType">
					<AInput
						:precision="0"
						v-if="show_planTenancyType"
						tag="price"
						type="number"
						:state="state"
						v-model="plan.planTenancyType"></AInput>
					<ASelectUni
						:state="state"
						v-else
						:dict="{
							list: dictList.planTenancyType,
						}"
						v-model="plan.planTenancyType"></ASelectUni>
				</FromItem>
				<FromItem
					label="支付时间"
					:required="true"
					:state="state"
					name="planPaymentMethodType">
					<template #labelIcon>
						<div>
							<uni-icons
								@click="click_planBillType('planPaymentMethodType')"
								type="help-filled"
								size="16"></uni-icons>
						</div>
					</template>
					<ASelectUni
						:state="state"
						:dict="{
							list: dict.type.quota_plan_payment_method,
						}"
						v-model="plan.planPaymentMethodType"></ASelectUni>
				</FromItem>
				<FromItem
					v-if="show_planCashdepositProportion"
					label="保证金比例（%）"
					:state="state"
					name="planCashdepositProportion">
					<AInput
						tag="price"
						type="number"
						:state="state"
						:min="0"
						:max="100"
						v-model="plan.planCashdepositProportion"
						:format="A_ratio(plan.planCashdepositProportion)"></AInput>
				</FromItem>
				<FromItem
					v-if="show_planContractCashdeposit"
					:keepRules="true"
					label="合同保证金"
					:required="true"
					:rawRules="true"
					:state="state_planContractCashdeposit"
					name="planContractCashdeposit">
					<AInput
						tag="price"
						type="number"
						:state="state_planContractCashdeposit"
						v-model="plan.planContractCashdeposit"
						@change="change_planContractCashdeposit"></AInput>
				</FromItem>
				<FromItem
					v-if="show_planViolationCashdeposit"
					label="违章保证金"
					:required="true"
					:state="state"
					name="planViolationCashdeposit">
					<AInput
						tag="price"
						type="number"
						:state="state"
						v-model="plan.planViolationCashdeposit"
						@change="change_planViolationCashdeposit"></AInput>
				</FromItem>
				<FromItem label="预计起租日期" :required="true" :state="state" name="planTimeStart">
					<ADatePicker
						:state="state"
						v-model="plan.planTimeStart"
						:format="A_formatTime(plan.planTimeStart, 0)"></ADatePicker>
				</FromItem>
				<FromItem
					label="每期租金"
					:required="true"
					:state="state"
					name="planRent"
					:keepRules="true">
					<AInput
						tag="price"
						type="number"
						:state="
							state == 'readonly'
								? 'readonly'
								: config.internalRateOfReturnCalcMethod == 1
								? 'write'
								: 'readonly'
						"
						v-model="plan.planRent"></AInput>
				</FromItem>
				<FromItem :required="true" label="账期" :state="state" name="planPeriod">
					<template #labelIcon>
						<div>
							<uni-icons
								@click="click_planBillType('planPeriod')"
								type="help-filled"
								size="16"></uni-icons>
						</div>
					</template>
					<AInput
						:precision="0"
						:state="state"
						type="number"
						v-model="plan.planPeriod"></AInput>
				</FromItem>
				<FromItem label="账单生成方式" :required="true" :state="state" name="planBillType">
					<template #labelIcon>
						<div>
							<uni-icons
								@click="click_planBillType('planBillType')"
								type="help-filled"
								size="16"></uni-icons>
						</div>
					</template>
					<ASelectUni
						:state="state"
						:dict="{
							list: dict.type.quota_plan_bill_type,
						}"
						v-model="plan.planBillType"></ASelectUni>
				</FromItem>
				<FromItem
					v-if="show_planTotalInvestment"
					label="公司投入总额"
					:required="true"
					:state="state"
					name="planTotalInvestment"
					:keepRules="true">
					<AInput
						tag="price"
						type="number"
						state="readonly"
						v-model="plan.planTotalInvestment"></AInput>
				</FromItem>
				<FromItem
					v-if="show_planFirstRentProportion"
					label="首期租金比例（%）"
					:state="state"
					name="planFirstRentProportion">
					<AInput
						tag="price"
						type="number"
						:min="0"
						:max="100"
						:precision="5"
						:state="state"
						v-model="plan.planFirstRentProportion"
						:format="A_ratio(plan.planFirstRentProportion)"></AInput>
				</FromItem>

				<FromItem
					v-if="show_planFirstRent"
					:state="state_planFirstRent"
					label="首期租金"
					:showRequiredIcon="true"
					:rawRules="true"
					name="planFirstRent">
					<AInput
						type="price"
						:state="state_planFirstRent"
						v-model="plan.planFirstRent"
						@change="change_planFirstRent"></AInput>
				</FromItem>
				<FromItem
					v-if="show_planPricingIrr"
					label="APR（%）"
					:required="true"
					:state="state"
					name="planPricingIrr">
					<AInput
						:state="state"
						type="number"
						:min="config.quotationProductSchemeRule.irrLowerLimit || 0"
						:max="100"
						v-model="plan.planPricingIrr"
						:format="A_ratio(plan.planPricingIrr)"></AInput>
				</FromItem>
				<FromItem
					v-if="show_planResidualProportion"
					label="残值比例（%）"
					:required="true"
					:state="state"
					name="planResidualProportion">
					<AInput
						:state="state"
						type="number"
						:min="0"
						:max="100"
						:precision="5"
						v-model="plan.planResidualProportion"
						:format="A_ratio(plan.planResidualProportion)"></AInput>
				</FromItem>
				<FromItem label="残值金额" state="readonly" name="planBalancepayment">
					<AInput
						type="number"
						tag="price"
						state="readonly"
						v-model="plan.planBalancepayment"></AInput>
				</FromItem>
				<FromItem label="是否包油费" :state="state" name="planFuelType" :required="true">
					<ARadioGroup
						:state="state"
						@change="change_planFuelType"
						v-model="plan.planFuelType"
						:dict="{
							list: dict.type.quota_plan_fuel_type,
						}"></ARadioGroup>
				</FromItem>
				<FromItem
					:required="true"
					label="油费"
					:state="state"
					name="planFuelFee"
					v-if="show_planFuelType">
					<AInput type="price" :state="state" v-model="plan.planFuelFee"></AInput>
				</FromItem>
				<FromItem
					label="备注"
					:state="state"
					name="remark"
					:required="true"
					v-if="show_planFuelType">
					<AInput
						:state="state"
						placeholder="请说明油费测算方法"
						v-model="plan.remark"></AInput>
				</FromItem>
				<FromItem label="是否含司机" :state="state" name="planDriverType" :required="true">
					<ARadioGroup
						:state="state"
						@change="change_planDriverType"
						v-model="plan.planDriverType"
						:dict="{
							list: dict.type.quota_plan_driver_type,
						}"></ARadioGroup>
				</FromItem>
				<FromItem
					:required="true"
					label="司机费用"
					:state="state"
					name="planDriverFee"
					v-if="show_planDriverType">
					<AInput type="price" :state="state" v-model="plan.planDriverFee"></AInput>
				</FromItem>
				<FromItem
					label="上传司机费用附件"
					:state="state"
					name="planDriverAccessory"
					:required="true"
					v-if="show_planDriverType">
					<ImageCommon
						v-model="plan.planDriverAccessory"
						:disabled="state !== 'write'"
						:upType="2"
						:maxCount="1"></ImageCommon>
				</FromItem>
			</uni-forms>
		</div>
		<uni-popup ref="popup" background-color="#fff">
			<view class="popup-content">
				<div class="text" v-if="type == 'planBillType'">
					<div>满月：起租日=8月8日，则满月计算是从8月8日开始到9月7日 （推荐选择）</div>
					<div>
						自然月：起租日=8月8日，则自然月计算是第一期是从8月8日开始到8月31日，第二期起是1日到31日，最后一期是1日到7日补齐第一期少的那几天。（不推荐）
					</div>
				</div>
				<div class="text" v-if="type == 'planPaymentMethodType'">
					<div>先付：起租日前支付为先付</div>
					<br />
					<div>后付：每期租期结束日后支付</div>
				</div>
				<div class="text" v-if="type == 'planPeriod'">
					<div>
						账期：起租日算起向后允许客户欠款的日期，支付时间选择后付的，相当于已经给客户30天的账期。
					</div>
					<br />
					<br />
					<div><b>举例:</b></div>
					<div>
						起租日为8月1日，付款日在8月31日前,选【月先付】【账期】应录入为【30天】;
					</div>
					<div>
						起租日为8月1日，付款日在9月30日前,选【月后付】【账期】应录入为【30天】;或【月先付】60天
					</div>
					<div style="color: #ff4949">注意：要与合同条件一致</div>
				</div>
				<div class="btn" @click="closeTip">确认</div>
			</view>
		</uni-popup>
	</div>
</template>

<script>
	import * as app from '@/api/index.js';
	import * as apis from '@/api/quota/apply/api.js';
	import * as utils from '@/pages/quota/libs/utils.js';
	import FromItem from '../formItem/index.vue';
	import Upload from '@/components/lr-upload.vue';
	export default {
		name: '',
		components: { FromItem, Upload },
		dicts: [
			'quota_plan_payment_frequency_type',
			'quota_plan_payment_method',
			'quota_plan_bill_type',
			'quota_plan_fuel_type',
			'quota_plan_driver_type',
		],
		props: {},
		inject: [
			'details_provide',
			'config_provide',
			'deptList_provide',
			'state_provide',
			'index_provide',
			'planDicts_provide',
			'fromtype_provide',
		],
		provide() {
			return {
				state_provide: 'test',
			};
		},
		data() {
			return {
				dictList: {
					planTenancyType: [
						{
							label: '6',
							value: '6',
						},
						{
							label: '12',
							value: '12',
						},
						{
							label: '24',
							value: '24',
						},
						{
							label: '36',
							value: '36',
						},
						{
							label: '48',
							value: '48',
						},
						{
							label: '60',
							value: '60',
						},
					],
					quota_plan_fuel_type: [
						{
							label: '是',
							vlaue: '1',
						},
						{
							label: '否',
							vlaue: '2',
						},
					],
					quota_plan_driver_type: [
						{
							label: '是',
							vlaue: '1',
						},
						{
							label: '否',
							vlaue: '2',
						},
					],
				},
				watchValue: {
					firstRent: null,
					Contract: null,
				},
				type: '',
			};
		},
		computed: {
			details() {
				return this.details_provide();
			},
			config() {
				return this.config_provide();
			},
			deptList() {
				return this.deptList_provide();
			},
			planDicts() {
				return this.planDicts_provide();
			},
			state() {
				return this.state_provide();
			},
			fromtype() {
				return this.fromtype_provide();
			},

			index() {
				return this.index_provide();
			},
			currentInfoData() {
				return this.details.productList?.[this.index] ?? {};
			},
			plan() {
				return this.currentInfoData?.plan ?? {};
			},
			firstInfoData() {
				return this.details.productList?.[0] ?? {};
			},
			show() {
				return this.details.rentType_raw == '2';
			},
			show_planTenancyType() {
				return this.config.quotationProductSchemeRule?.openTermModification == 1;
			},
			show_planCashdepositProportion() {
				return this.config?.businessSource == '1' && this.details?.rentType_raw == '2';
			},
			show_planContractCashdeposit() {
				return (
					this.config?.quotationProductSchemeAttributeOption?.hasContractDepositOptions?.includes(
						1,
					) ||
					this.config?.quotationProductSchemeAttributeOption?.hasContractDepositOptions?.includes(
						'1',
					)
				);
			},
			state_planContractCashdeposit() {
				return this.state;
				return this.state == 'readonly'
					? 'readonly'
					: this.config?.quotationProductSchemeRule?.openContractDepositModification == 1
					? 'write'
					: 'readonly';
			},
			show_planViolationCashdeposit() {
				return (
					this.config.businessSource == '1' &&
					this.config?.quotationProductSchemeAttributeOption?.hasViolationDepositOptions?.includes(
						1,
					)
				);
			},
			show_planTotalInvestment() {
				return this.config?.businessSource == '1' && this.details?.rentType_raw == '2';
			},
			show_planFirstRentProportion() {
				return this.details?.rentType_raw == '2';
			},
			show_planFirstRent() {
				return this.details?.rentType_raw == '2';
			},
			show_planPricingIrr() {
				return (
					(this.details?.rentType_raw == '2' &&
						this.type !== 'readonly' &&
						this.config?.businessSource == '1') ||
					this.config?.internalRateOfReturnCalcMethod == 3
				);
			},
			show_planResidualProportion() {
				return this.details?.rentType_raw == '2';
			},
			show_planFuelType() {
				return this.plan?.planFuelType == '1';
			},
			show_planDriverType() {
				return this.plan?.planDriverType == '1';
			},
			state_planFirstRent() {
				return this.state;
				return this.state == 'readonly'
					? 'readonly'
					: this.config?.quotationProductSchemeRule?.openInitialRentModification == 1
					? 'wirte'
					: 'readonly';
			},
			rule_planFirstRent() {
				let that = this;
				return (rule, value, data, callback) => {
					let priceLine = 0,
						monthRent = 0;

					let ratio =
						this.config?.quotationProductSchemeRule?.initialRentMinimumRentMonths ?? 0;
					if (this.currentInfoData?.plan?.planRent) {
						monthRent = utils.toNumberExcept(
							this.currentInfoData?.plan?.planRent,
							this.currentInfoData?.plan?.planPaymentFrequencyType * 1,
						);
						if (monthRent) {
							priceLine = utils.toNumberRide(monthRent, ratio);
						}
					}
					if (!Number.isFinite(priceLine)) {
						priceLine = 0;
					}
					if (this.currentInfoData?.plan?.planFirstRent < priceLine.toFixed(2) * 1) {
						callback(`不能低于${ratio}个月月租金（￥${priceLine.toFixed(2)}）`);
					} else {
						return true;
					}
				};
			},
			rule_planContractCashdeposit() {
				this.config?.quotationProductSchemeRule?.contractDepositMinimumRentMonths;

				this.plan?.planRent;
				this.plan?.planPaymentFrequencyType;
				this.plan?.planContractCashdeposit;
				return (rule, value, data, callback) => {
					let priceLine = 0,
						monthRent = 0;

					let ratio =
						this.config?.quotationProductSchemeRule?.contractDepositMinimumRentMonths ??
						0;
					if (this.plan?.planRent) {
						monthRent = utils.toNumberExcept(
							this.plan?.planRent,
							this.plan?.planPaymentFrequencyType * 1,
						);
						if (monthRent) {
							priceLine = utils.toNumberRide(monthRent, ratio);
						}
					}
					if (!Number.isFinite(priceLine * 1)) {
						priceLine = 0;
					}

					if (this?.plan?.planContractCashdeposit < priceLine.toFixed(2) * 1) {
						callback(`不能低于${ratio}个月月租金（￥${priceLine.toFixed(2)}）`);
					} else {
						return true;
					}
				};
			},
		},

		watch: {},
		filters: {},
		created() {},
		mounted() {
			this.watchRules();
			// this.$watch(
			// 	'config',
			// 	val => {
			// 		this.watchRules();
			// 	},
			// 	{
			// 		immediate: true,
			// 		deep: true,
			// 	},
			// );
		},
		methods: {
			watchRules() {
				this.watchValue.firstRent?.();
				this.watchValue.Contract?.();
				this.watchValue.firstRent = this.$watch(
					'show_planFirstRent',
					val => {
						this.setRules_FirstRent(val);
					},
					{
						immediate: true,
						deep: true,
					},
				);
				this.watchValue.Contract = this.$watch(
					'show_planContractCashdeposit',
					val => {
						this.setRules_Contrac(val);
					},
					{
						immediate: true,
						deep: true,
					},
				);
			},
			setRules_Contrac(show) {
				if (show) {
					let v = [];
					if (
						this.config?.quotationProductSchemeRule?.openContractDepositModification ==
						1
					) {
						v = [
							{
								required: true,
								errorMessage: '请输入合同保证金',
							},
						];
					} else {
						v = [
							{
								required: true,
								errorMessage: '请输入合同保证金',
							},
							{
								validateFunction: this.rule_planContractCashdeposit,
							},
						];
					}
					this.setRules('planContractCashdeposit', v);
				} else {
					this.setRules('planContractCashdeposit', []);
				}
			},
			setRules_FirstRent(show) {
				if (show) {
					let v = [];
					if (this.config?.quotationProductSchemeRule?.openInitialRentModification == 1) {
						v = [
							{
								required: true,
								errorMessage: '请输入首期租金',
							},
						];
					} else {
						v = [
							{
								required: true,
								errorMessage: '请输入首期租金',
							},
							{
								validateFunction: this.rule_planFirstRent,
							},
						];
					}

					this.setRules('planFirstRent', v);
				} else {
					this.setRules('planFirstRent', []);
				}
			},
			click_planBillType(type) {
				this.type = type;
				this.$refs.popup.open();
			},
			closeTip() {
				this.$refs.popup.close();
			},
			setRules(prop, rules) {
				if (!prop) return;
				if (!Array.isArray(rules)) rules = [];
				if (
					((!('prop' in this.$refs?.form?.formRules) ||
						this.$refs?.form?.formRules?.[prop]?.rules?.length == 0) &&
						rules?.length > 0) ||
					rules?.length == 0
				) {
					this.$refs.form.setRules({
						[prop]: {
							rules: rules,
						},
					});
				}
			},
			change_planContractCashdeposit(val) {
				if (this.notEmpty(val)) {
					this.currentInfoData.planConf.planContractCashdeposit_state = 'changed';
				} else {
					this.currentInfoData.planConf.planContractCashdeposit_state = '';
				}
				this.$set(this.currentInfoData.plan, 'planCashdepositProportion', undefined);
			},
			change_planViolationCashdeposit(val) {
				if (this.notEmpty(val)) {
					this.currentInfoData.planConf.planViolationCashdeposit_state = 'changed';
				} else {
					this.currentInfoData.planConf.planViolationCashdeposit_state = '';
				}
			},
			change_planFirstRent(val) {
				if (this.notEmpty(val)) {
					this.currentInfoData.planConf.planFirstRent_state = 'changed';
				} else {
					this.currentInfoData.planConf.planFirstRent_state = '';
				}
				this.$set(this.plan, 'planFirstRentProportion', undefined);
			},

			change_planFuelType() {
				this.currentInfoData.plan.planFuelFee = undefined;
				this.currentInfoData.plan.remark = undefined;
			},
			change_planDriverType() {
				this.currentInfoData.plan.planDriverFee = undefined;
				this.currentInfoData.plan.planDriverAccessory = undefined;
			},

			A_ratio(val) {
				return val ?? '-' + '%';
			},
		},
	};
</script>

<style lang="scss" scoped>
	.box {
		// margin: 20rpx;
		// padding: 20rpx;
		padding-top: 20rpx;
		background-color: #fff;
		border-radius: 8rpx;
		.title {
			border-bottom: 1px solid #e9e9e9;
			font-weight: 500;
			padding-bottom: 10rpx;
			margin-bottom: 10rpx;
		}
	}
	.popup-content {
		padding: 45rpx;
		padding-bottom: 0;
		box-sizing: border-box;
		width: 80vw;
		background-color: #fff;
		border-radius: 15rpx;
		min-height: 200rpx;
		.text {
			font-size: 16px;
			padding-bottom: 25rpx;
			overflow-y: auto;
			max-height: 500rpx;
			color: #909399;
			div {
				text-indent: 4ch;
			}
		}
		.btn {
			border-top: 1px solid #ccc;
			padding: 30rpx 0;
			text-align: center;
			color: #007aff;
			font-size: 14px;
		}
	}
</style>
